<template>
  <section class="blog-one">
    <div class="tab-box">
      <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="应用模板" name="1"></el-tab-pane>
          <el-tab-pane label="设计素材" name="2"></el-tab-pane>
          <!-- <el-tab-pane label="主题资源" name="3"></el-tab-pane>-->
        </el-tabs>
      </div>
      <div style="padding: 10px 0px;width: 100%;margin: auto;border-bottom: 1px solid rgb(234, 236, 238);">
        <div class="tags_wrapper market_tagsStyle">
          <div class="tags_title">{{typeTitle1}}</div>
          <ul>
            <li :class="[index==activeIndex1?'tags_active':'']" v-for="(item,index) in typeList1" @click="checktype1(item.key,index)">{{item.value}}</li>
          </ul>
        </div>
        <div class="tags_wrapper market_tagsStyle" v-if="activeName==1">
          <div class="tags_title">{{typeTitle2}}</div>
          <ul>
            <li :class="[index==activeIndex2?'tags_active':'']" v-for="(item,index) in scenarioOptions" @click="checktype2(item.key,index)">{{item.value}}</li>
          </ul>
        </div>
        <div class="tags_wrapper market_tagsStyle" v-if="activeName==1">
          <div class="tags_title">{{typeTitle3}}</div>
          <ul>
            <li :class="[index==activeIndex3?'tags_active':'']" v-for="(item,index) in industryOptions" @click="checktype3(item.key,index)">{{item.value}}</li>
          </ul>
        </div>
      </div>

    </div>
    
    <div style="width:95%;margin: 0 auto;display:flex;">
      <div style="margin: 20px;">
          <el-select v-model="queryParams.orderBy" placeholder="请选择" @change="changeOrder">
            <el-option
              v-for="item in sortOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">

            </el-option>
          </el-select>
      </div>
      <div style="margin: 20px 0;">
          <el-select v-model="queryParams.queryType" placeholder="请选择" @change="changeQueryType">
            <el-option label="全部" value="1"></el-option>
            <el-option label="我的收藏" value="2"></el-option>
          </el-select>
      </div>      
    </div>

     <div id="container" class="container" :style="getContainerStyle">
      <div id="innerBox" style="height: 700px;overflow-y: auto;">
    
        <ul class="row"
              v-infinite-scroll="load"
              infinite-scroll-disabled="disabled">
          <li class=" wow fadeInUp" v-for="(item,index) in templateList" :key="index" @mouseenter="enterBox(index)" @mouseleave="leaveBox(index)" @click="viewMaterial(item)">
            <div class="blog-one__single">
              <div class="blog-one__image">
                <div class="image-shadow" :id="['shadow'+index]">
                    <div style="display:flex;float: right;margin-top: 7px;">

                      <div class="bubble" @click.stop="starMaterial(item)"><i :class="getStarClass(item)"></i></div>
                      <div class="bubble" @click.stop="createMaterial(item)"><i class="el-icon-copy-document" style="font-size:24px"></i></div>
                    </div>
                </div>
                <img :src="basePath + item.capturePath" v-if="activeName==1">
                <img :src="basePath + item.imagePath" v-if="activeName==2" class="market_itemImg">
                <a class="blog-one__more-link" href="news-details.html"><i class="fa fa-link"></i>
                  </a>
              </div>
              <div class="blog-one__content">

                <h3 class="blog-one__title" :title="item.screenName" v-if="activeName==1">
                  {{item.screenName}}
                </h3>
                <h3 class="blog-one__title" :title="item.name" v-if="activeName==2">
                  {{item.name}}
                </h3>
                <ul class="list-unstyled blog-one__meta">
                  <li><a>{{item.starCount}}次收藏</a></li>
                  <li><a>{{item.useCount}}次使用</a></li>
                </ul>
                
              </div>
            </div> 
          </li>
        </ul>
        <!-- <p v-if="loading" style="text-align: center;">加载中...</p> -->
        <p v-if="noMore && templateList.length != 0" style="text-align: center;">没有更多了</p>
      
      </div>
      <div v-if="emptyFlag" style="position:absolute;top:10%;left:40%;width:226px;display:flex;flex-direction: column;">
        <div>
          <img src="../image/empty.png" alt="富表可视化平台">
        </div>
        <div style="color: #262c33;font-weight: 500;font-size: 18px;">
          很抱歉，没有找到相关内容
        </div>
        <div style="margin-top: 8px;color: #757881;font-weight: 400;font-size: 14px;line-height: 20px;">
          找不到想要的模板？请
          <span style="color: #007afc;text-decoration: underline;cursor: pointer;transition: .3s;" @click="openDemand()">告诉我们</span>~
        </div>
      </div>
    </div>
  </section>
</template>

<script>

import * as templateMethods from "@/api/tool/datav/cmsTemplateInfo";
import { fileTemplateList,updateTemplate,addUpload } from "@/api/tool/datav/fileUpload";
import VueEvent from '@/views/tool/datav/VueEvent'
import * as cmsTemplateMethods from "@/api/tool/datav/cmsTemplateInfo"
import { addFavorite,userFavoriteList } from "@/api/tool/datav/favorite"
    export default {
      name: "Material",
      data() {
        return {
          screenWidth: document.body.clientWidth,
          basePath: process.env.VUE_APP_BASE_API,
          activeName: '1',//当前选中选项卡
          typeTitle1: "类型",
          typeTitle2: "场景",
          typeTitle3: "行业",
          typeList1:[{
            "key":"",
            "value":"全部"
          },
          {
            "key":"PC",
            "value":"PC端"
          },
          {
            "key":"Phone",
            "value":"移动端"
          }],
          typeList2:["全部","行业模板","数据运营","实操教程"],
          typeList3:["全部","水利环境","运维监管","医疗健康","其他"],
          activeIndex1:0,
          activeIndex2:0,
          activeIndex3:0,
          sortOptions:[
            {
              value: '0',
              label: '热门推荐'
            },
            {
              value: '1',
              label: '最新发布'
            },
          ],
          queryParams:{
            pageNum: 1,
            pageSize: 10,
            keyword:"",//关键字
            orderBy:"0",//排序
            isReleased:"1",//已发布
            belongto:null,//分类 
            deviceType:null,//设备类型
            scenario:null,//场景
            industry:null,//行业
            type:null,//0 背景 1边框
            sort: null,//图片分类
            name:null,//图片名称
            queryType:"1",//是否收藏
          },
          templateList:[],
          loading: false,
          total: -1,
          industryOptions:[],//模板行业
          scenarioOptions:[],//模板使用场景
          itemIsExisted:false,//是否被收藏标识符
          emptyFlag:false,
          starTemplateList:[],//收藏模板列表
          starFileList:[],//收藏素材列表
        }
      },
      computed: {
        noMore () {
          if(this.total != -1) {
            return this.total == this.templateList.length
          } else {        
            return false;
          }
        },
        disabled () {
          if(this.templateList.length == 0){
            this.emptyFlag = true;
          }else{
            this.emptyFlag = false;
          }
          return this.loading || this.noMore
        },
        getContainerStyle(){
           let style = {overflow: "hidden"}

          if(this.templateList.length == 0){
            style.height = "300px"
          }else{
            style.height = "700px"
          }
          return style
        }
      },
      mounted() {
        this.activeName = this.$route.params.type || '1'
        //设置隐藏滚动条
        document.getElementById("container").style.width = (document.body.clientWidth * 0.95) + "px";
        document.getElementById("innerBox").style.width = (document.body.clientWidth * 0.98) + "px"

        //获取行业类型
        this.getDicts("cms_template_industry").then(response => {
          this.industryOptions.push({"key":"","value":"全部"})
          response.data.forEach(element => {
            this.industryOptions.push({"key":element.dictValue,"value":element.dictLabel})
          });
        });
        //获取场景类型
        this.getDicts("cms_template_scenario").then(response => {
          this.scenarioOptions.push({"key":"","value":"全部"})
          response.data.forEach(element => {
           this.scenarioOptions.push({"key":element.dictValue,"value":element.dictLabel})
          });
        });

        this.reload();

        userFavoriteList().then(response => {
          if(response.code == 200){
            if(response.data.file){
              this.starFileList = response.data.file;
            }
            if(response.data.screen){
              
              this.starTemplateList = response.data.screen;
            }


          }
        });
        //监听输入框搜索
        VueEvent.$on('material-search',function(item){
            if(this.activeName == 1){
              this.queryParams.keyword = item;
            }else{
              this.queryParams.name = item;
            }

            this.reload();
                            
        }.bind(this))
      },
      methods: {
        //重置查询
        reload(){
          this.total = -1;
          this.templateList = [];
          this.queryParams.pageNum = 1;
          this.load();
        },
        //切换选项卡
        handleClick(tab){
          if(tab.index == 0){
            this.typeTitle1 = "类型";
            this.typeList1 = [{
              "key":"",
              "value":"全部"
            },
            {
              "key":"PC",
              "value":"PC端"
            },
            {
              "key":"Phone",
              "value":"移动端"
            }];

          }else if(tab.index == 1){
            this.typeTitle1 = "素材";
            this.activeIndex1 = 0;
            this.typeList1 =[{value:'全部', key: ""},{value:'背景', key: "0"},{value:'图标', key: "1"}, {value:'边框', key: "2"}, {value:'按钮', key: "3"}];
          }
           VueEvent.$emit('clear-search')
          this.reload();
        },
        changeOrder(){
          this.reload();
        },
        //切换设备类型
        checktype1(item,index){
          this.activeIndex1 = index;
          if(this.activeName == 1){

            this.queryParams.deviceType = item;
          }else{
            //背景
            if(item == "0"){
              this.queryParams.type = "0";
            }
            //图标
            else{
              this.queryParams.type = "1";
              this.queryParams.sort = item;
            }
          }
          this.reload();
        },
        //切换场景
        checktype2(item,index){
          this.activeIndex2 = index;
          this.queryParams.scenario = item;
          this.reload();
        },
        //切换行业
        checktype3(item,index){
          this.activeIndex3 = index;
          this.queryParams.industry = item;
          this.reload();
        },
        enterBox(index){
          document.getElementById('shadow'+index).style.display = "block";
        },
        leaveBox(index){
          document.getElementById('shadow'+index).style.display = "none";
        },
        load () {
          this.loading = true;
          if(this.activeName==1){
            //获取模板列表
            templateMethods.userTemplateList(this.queryParams).then(response => {
              if (response.code == 200) {
                this.templateList =this.templateList.concat(response.rows);;
                this.total = response.total;
                this.queryParams.pageNum++;
                this.loading = false;
              }
            });
          }else{
            //获取素材列表
            fileTemplateList(this.queryParams).then(response => {
              if (response.code == 200) {
                this.templateList =this.templateList.concat(response.rows);
                this.total = response.total;
                this.queryParams.pageNum++;
                this.loading = false;
              }
            });           
          }
                
        }, 
        pageCount (totalnum, limit) {
            return totalnum > 0 ? ((totalnum < limit) ? 1 : ((totalnum % limit) ? (parseInt(totalnum / limit) + 1) : (totalnum / limit))) : 0;
        }, 
        //查看详情
        viewMaterial(item){
          let id = "";
          //更新应用模板查看数
          if(this.activeName == 1){
              id = item.id;
              let viewData = {screenId:item.screenId }
              cmsTemplateMethods.viewCountIncrease(viewData).then(res => {
                if(res.code == 200){
                  
                }
              })
          }
          //更新图片素材查看数
          else if(this.activeName == 2){
            id = item.uploadId;
            let data = {"uploadId":item.uploadId,"type":1};
            updateTemplate(data).then(response => {
              if (response.code == 200) {
              }
            }); 
          }
          const viewRuter = this.$router.resolve({path: "/cms/template", query: {id: id,type:this.activeName}})
          window.open(viewRuter.href,'_self')

        },
        //收藏模板
        starMaterial(item){
          //更新应用模板收藏数
          let starData = {}
          if(this.activeName == 1){
            starData = {screenId:item.screenId }
          }
          //更新图片素材收藏数
          else if(this.activeName == 2){
            starData = {imageUploadId:item.uploadId } 
          }
          addFavorite(starData).then(response => {
              if(response.code = 200){
                  if(this.activeName == 1){
                  //收藏模板
                  if(response.data){
                    cmsTemplateMethods.starCountIncrease(starData).then(res => {
                      if(res.code == 200){
                        this.starTemplateList.push({imageUploadId:null,screenId:item.screenId})
                        this.msgSuccess("收藏成功");
                      }else{
                        this.msgError("收藏失败");
                      }
                    })
                  }else{
                    cmsTemplateMethods.starCountDecrease(starData).then(res => {
                      if(res.code == 200){

                          let index = this.starTemplateList.findIndex(ele => ele.screenId === item.screenId)
                          
                          this.starTemplateList.splice(index,1)
                        this.msgSuccess("取消收藏");
                      }else{
                        this.msgError("取消收藏失败");
                      }
                    })
                  }

                }
                //更新图片素材收藏数
                else if(this.activeName == 2){
                  let data = {"uploadId":item.uploadId};
                  //收藏
                  if(response.data){

                    data.type = 2
                  }
                  else{
                    data.type = 3
                  }
                  updateTemplate(data).then(res => {
                    if (response.data && res.code == 200) {
                      //添加进收藏列表
                      this.starFileList.push({imageUploadId:item.uploadId,screenId:null})

                      this.msgSuccess("收藏成功");
                    }else if(response.data && res.code != 200){
                      this.msgError("收藏失败");
                    }else if(!response.data && res.code == 200){
                      //从收藏列表中删除

                      let index = this.starFileList.findIndex(ele => ele.imageUploadId === item.uploadId)
                        
                      this.starFileList.splice(index,1)

                      this.msgSuccess("取消收藏");
                    }else if(!response.data && res.code != 200){
                      this.msgError("取消收藏失败");
                    }
                  }); 
                }
                // this.reload();
              }
          })

        },
        //创建模板
        createMaterial(item){
          //更新应用模板创建数并创建大屏
          if(this.activeName == 1){
            let query = { screenId:item.screenId }
            cmsTemplateMethods.useCountIncrease(query).then(res => {
                this.$router.push({path: '/tool/datav/datavDraw', query: {screenId: '', temlateId: item.screenId}});
            })
          }
          //更新图片素材创建数
          else if(this.activeName == 2){
            let data = {"uploadId":item.uploadId,"type":4};
            updateTemplate(data).then(response => {
              if (response.code == 200) {
                item.createBy = this.$store.getters.name;
                addUpload(item).then(response => {
                  if (response.code == 200) {
                    this.msgSuccess("创建成功");
                  }
                });
              }
            }); 
          }
        },
        //获取收藏样式
        getStarClass(item){
          if(this.activeName == 1){
            let result = this.starTemplateList.find(ele => ele.screenId === item.screenId)//判断是否包含大屏id
            if(result){
              return "el-icon-star-on"
            }else{
              return "el-icon-star-off"
            }
          }else if(this.activeName == 2){
            let result = this.starFileList.find(ele => ele.imageUploadId === item.uploadId)//判断是否包含图片id
            if(result){
              return "el-icon-star-on"
            }else{
              return "el-icon-star-off"
            }
          }
        },
        changeQueryType(){
          this.reload();
        },
        openDemand(){
          const viewRuter = this.$router.resolve({path: "/cms/demand"})
          window.open(viewRuter.href,'_blank')
        }      
      },
    }
</script>

<style scoped>
.tab-box{
  width: 95%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}
.tags_wrapper{
  display: flex;
  margin: auto;
  margin-bottom: 20px;
}
.tags_title {
  min-width: 58px;
  margin-top: 0;
  color: #878a8e;
  font-weight: 400;
  font-size: 14px;
  line-height: 28px;
}
.tags_active {
  color: #3a89fe!important;
  font-weight: 600!important;
  background: rgba(58,137,254,.06);
}

.tags_wrapper ul {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  margin: 0;
  padding: 0;
}
.tags_wrapper ul li {
  list-style: none;
  height: 28px!important;
  margin: 0!important;
  padding: 0 12px!important;
  color: #4d5258;
  font-weight: 400;
  font-size: 14px!important;
  line-height: 28px!important;
  transition: .3s;
  position: relative;
  text-align: center;
  border-radius: 2px;
  cursor: pointer;
}
.blog-one__content {
  border-style: solid;
  border-width: 1px;
  border-color: #efefef;
  background-color: white;
  border-top: 0;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding: 10px 10px 20px 10px;
  cursor: pointer;

}
.blog-one .container{
    position: relative;
    max-width: 95%;
    margin: auto;
    overflow: hidden;
    /* margin-right: 0%; */
}
.wow{
    width: 18%;
    margin-right: 25px;
}
.row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: 0px;
    margin-left: 0px;
}
.blog-one .container {
  position: relative;
  max-width: 95%;
}
.blog-one {
  padding: 20px 0;
}
.blog-one__title {
  font-weight: 500;
  font-size: 20px;
  line-height: 36px;
  color: #2a2833;
  margin: 0;
  margin-top: 5px;
  margin-bottom: 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.blog-one__image {
    position: relative;
    background-color: #ffffff;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    height: 185px;
}
.image-shadow{
  width: 100%;
  height: 100%;
  background-color: #221b1b4d;
  position:absolute;
  top: 0px;
  z-index: 2;
  display: none;
}
.blog-one__image>img {
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    width: 100%;
    -webkit-transition: all .4s ease;
    transition: all .4s ease;
    height: 100%;
}
.blog-one__single:hover .blog-one__more-link {
  color: rgba(255, 255, 255, 0);
  opacity: 1;
}
.blog-one__single:hover .blog-one__image > img {
  opacity: 1;
}
.bubble{   
  width: 40px;      
  height: 40px;      
  background-color: rgba(255,255,255,.88);
  padding: 6px;
  border-radius: 50%;      
  -moz-border-radius: 50%;      
  -webkit-border-radius: 50%;    
  text-align: center;
  color: rgb(0,0,0);
  margin-right: 5px;    
} 
.bubble:hover{ 
  background-color: rgba(255,255,255,1);
}
.row li{
  list-style: none;
}
.el-icon-star-off{
  font-size: 24px;
}
.el-icon-star-on{
  font-size: 26px;
  color: #ffe156;
}
.market_itemImg{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #000;
}
</style>
